package com.zengfa.task.server.config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.DatabaseMetaData;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;

public class TableInitConfig implements ApplicationRunner {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		DatabaseMetaData metaData = jdbcTemplate.getDataSource().getConnection().getMetaData();
		String databaseProductName = metaData.getDatabaseProductName();
		if ("H2".equals(databaseProductName)) {
			initH2Db();
		}else if("MySQL".equals(databaseProductName)) {
			
		}
	}
	
	private void initH2Db() throws IOException{
		System.out.println("初始化H2数据库");
		Resource resource = new ClassPathResource("db/h2/ddl.sql");
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
			String content = reader.lines().collect(Collectors.joining(System.lineSeparator()));
			jdbcTemplate.execute(content);
        }
	}

}
